<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 16-12-12
 * Time: 上午11:01
 */

namespace common\repositories\outstock;


use common\entities\outstock\MyscrmOutStockProductEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use yii\helpers\Json;

class OutStockProductRepository extends BaseRepository
{
    /**
     * @inheritdoc
     */
    public function batchSave($orderId, $models)
    {
        foreach ($models as $model) {
            /** @var MyscrmOutStockProductEntity $model */
            $model->id = StringHelper::uuid();
            $model->order_id = $orderId;
            $model->bind_project = $model->bind_project ? Json::encode($model->bind_project) : null;
            if (!$model->validate() || !$model->save()) {
                $errors = $model->getFirstErrors();

                return self::setAndReturn(__LINE__, array_shift($errors));
            }
        }

        return true;
    }

    /**
     * 删除
     * @param $orderId
     * @return int
     */
    public function deleteByOrderId($orderId)
    {
        return MyscrmOutStockProductEntity::deleteAll([
            'order_id' => $orderId,
        ]);
    }

    /**
     * 获取所有产品
     * @param $orderId
     * @return MyscrmOutStockProductEntity[]
     */
    public function getProductsByOrderId($orderId)
    {
        $data = MyscrmOutStockProductEntity::find()->where(["order_id" => $orderId])->all();

        foreach ($data as &$item) {
            /** @var MyscrmOutStockProductEntity $item */
            $item->bind_project = Json::decode($item->bind_project);
        }

        return $data;
    }
}